<template>
  <div>
    <h1>数据展示</h1>
    <div class="latest-data">
      <h2>最新数据</h2>
      <ul>
        <li v-for="(value, key) in latestData" :key="key">{{ key }}: {{ value }}</li>
      </ul>
    </div>

    <div class="history-chart">
      <h2>{{ selectedDataType }} 历史数据</h2>
      <div ref="chart" style="width: 100%; height: 400px;"></div>
    </div>

    <div class="data-type-selector">
      <label for="dataType">选择数据类型:</label>
      <select v-model="selectedDataType" id="dataType" @change="loadHistoryData">
        <option value="temperature">温度</option>
        <option value="humidity">湿度</option>
        <option value="light">光照</option>
      </select>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchLatestData, fetchHistoryData } from '@/utils/api';

export default {
  data() {
    return {
      latestData: {},
      selectedDataType: 'temperature',
      chartInstance: null,
    };
  },
  methods: {
    async loadLatestData() {
      try {
        const response = await fetchLatestData();
        this.latestData = response.data;
      } catch (error) {
        console.error('获取最新数据失败:', error);
      }
    },
    async loadHistoryData() {
      try {
        const response = await fetchHistoryData(this.selectedDataType);
        this.renderChart(response.data);
      } catch (error) {
        console.error('获取历史数据失败:', error);
      }
    },
    renderChart(data) {
      const option = {
        title: { text: `${this.selectedDataType} 历史数据` },
        xAxis: { type: 'category', data: data.map((item) => item.timestamp) },
        yAxis: { type: 'value' },
        series: [{ data: data.map((item) => item.value), type: 'line' }],
      };
      this.chartInstance.setOption(option);
    },
  },
  mounted() {
    this.chartInstance = echarts.init(this.$refs.chart);
    this.loadLatestData();
    this.loadHistoryData();
  },
};
</script>

<style scoped>
h1 {
  text-align: center;
}
.latest-data, .history-chart {
  margin: 20px 0;
}
.data-type-selector {
  margin-top: 20px;
  text-align: center;
}
</style>
